package com.ssh.action;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.opensymphony.xwork2.ActionSupport;
import com.ssh.entity.Address_List;
import com.ssh.service.UserService;

public class AddSubmit extends ActionSupport {
	@Autowired
	private UserService userService;
	
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String addSubmit() throws IOException{
		HttpServletRequest request=ServletActionContext.getRequest();
		String name=request.getParameter("name");
		String phone=request.getParameter("phone");
		String company=request.getParameter("company");
		String e_mail=request.getParameter("e_mail");
		String address=request.getParameter("address");
		String relation=request.getParameter("relation");
		String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
		String newFileName=UUID.randomUUID()+uploadFileName.substring(uploadFileName.lastIndexOf("."));
		Address_List al=new Address_List();
		al.setName(name);
		al.setPhone(phone);
		al.setCompany(company);
		al.setE_mail(e_mail);
		al.setAddress(address);
		al.setRelation(relation);
		al.setImage(newFileName);
		File file = new File(realPath);
		if(upload != null) {
	        File saveFile = new File(file, newFileName);
	        if(!saveFile.getParentFile().exists()) {
	            saveFile.getParentFile().mkdir();
	        }
	        FileUtils.copyFile(upload,saveFile);
	    }   
		userService.save(al);
		return "add_success";
	}
}
